package utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Author: xiaoma
 * @Date: 2021/8/13 14:28
 * @description:
 */
public class JwtUtils {

    //token过期时间
    public static final long EXPIRE = 1000 * 60 * 60 * 24;
    //密钥
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";

    /**
     * @param id
     * @param userName
     * @return java.lang.String
     * @Description 生成token字符串
     * @Author Xiaoma
     * @Date 2021/8/13 14:58
     **/
    public static String getJwtToken(String id, String userName) {

        String JwtToken = Jwts.builder()
                //设置token头信息
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                //设置过期时间
                .setSubject("user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                //存储用户信息
                .claim("id", id)
                .claim("userName", userName)

                .signWith(SignatureAlgorithm.   HS256, APP_SECRET)
                .compact();

        return JwtToken;
    }

    /**
     * @Description 判断token是否存在与有效
     * @Author Xiaoma
     * @Date 2021/8/13 15:01
     * @param jwtToken
     * @return boolean
     **/
    public static boolean checkToken(String jwtToken) {
        if (StringUtils.isEmpty(jwtToken)) return false;
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

   /**
    * @Description 判断token是否存在与有效
    * @Author Xiaoma
    * @Date 2021/8/13 15:01
    * @param request
    * @return boolean
    **/
    public static boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("token");
            if (StringUtils.isEmpty(jwtToken)) return false;
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * @Description 根据token获取用户ID
     * @Author Xiaoma
     * @Date 2021/8/13 15:02
     * @param request
     * @return java.lang.String
     **/
    public static String getMemberIdByJwtToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("token");
        if (StringUtils.isEmpty(jwtToken)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("id");
    }
}
